package controller

import (
	"gitee.com/fanchenggang/SecKill/proxy/service"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
	"strconv"
	"strings"
	"time"
)

type SkillController struct {
	beego.Controller
}

func (p *SkillController) SecKill() {
	productId, err := p.GetInt("product_id")
	result := make(map[string]interface{})
	result["code"] = 0
	result["message"] = "success"
	if err != nil {
		result["code"] = 1001
		result["message"] = "Invalid productId"
		return
	}

	defer func() {
		p.Data["json"] = result
		p.ServeJSON()
	}()

	source := p.GetString("src")
	authCode := p.GetString("authcode")
	secTime := p.GetString("time")
	nance := p.GetString("nance")

	userId, err := strconv.Atoi(p.Ctx.GetCookie("userId"))
	if err != nil {
		result["code"] = service.ErrInvalidRequest
		result["message"] = err.Error()
		return
	}
	remoteAddr := p.Ctx.Request.RemoteAddr
	clientAddr := ""
	if len(remoteAddr) > 0 {
		clientAddr = strings.Split(p.Ctx.Request.RemoteAddr, ":")[0]
	}
	secRequest := &service.SecRequest{
		ProductId:     productId,
		AuthCode:      authCode,
		SecTime:       secTime,
		Nance:         nance,
		Source:        source,
		UserAuthSign:  p.Ctx.GetCookie("userAuthSign"),
		UserId:        userId,
		AccessTime:    time.Now(),
		ClientAddr:    clientAddr,
		ClientReferer: p.Ctx.Request.Referer(),
	}
	logs.Debug("client request:[%v]", secRequest)
	data, code, err := service.SecKill(secRequest)
	if err != nil {
		result["message"] = err.Error()
	}
	result["code"] = code
	result["data"] = data
	return
}

func (p *SkillController) SecInfo() {
	productId, err := p.GetInt("productId")
	result := make(map[string]interface{})
	result["code"] = 0
	result["message"] = "success"
	if err != nil {
		data, code, err := service.SecInfoList()
		if err != nil {
			result["code"] = code
			result["message"] = err.Error()
		}
		result["data"] = data
	} else {
		data, code, err := service.SecInfoById(productId)
		if err != nil {
			result["code"] = code
			result["message"] = err.Error()
		}
		result["data"] = data
	}

	p.Data["json"] = result
	p.ServeJSON()

}
